<template>
  <div class="admin-manage">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-content d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
          <i class="fa fa-crown mr-3 text-primary" style="font-size: 28px;"></i>
          <h2>管理员管理平台</h2>
        </div>
        <div class="d-flex align-items-center">
          <div class="weather-info mr-4">
            <i class="fa fa-sun text-yellow-500 mr-1"></i>
            <span>{{ weatherInfo.temp }}°C | {{ weatherInfo.description }}</span>
          </div>
          <button @click="logout" class="btn btn-danger">
            <i class="fa fa-sign-out mr-2"></i>退出登录
          </button>
        </div>
      </div>
    </header>

    <!-- 欢迎信息 -->
    <div class="welcome-section mt-4 p-4 bg-white rounded-lg shadow-sm">
      <div class="d-flex flex-wrap justify-content-between align-items-center">
        <div>
          <p class="mb-1">欢迎回来，<strong>{{ adminName }}</strong>！</p>
          <p class="text-muted mb-0">您的身份是：<span class="badge bg-primary">系统管理员</span></p>
        </div>
        <div class="mt-2 mt-md-0">
          <div class="d-flex align-items-center">
            <i class="fa fa-calendar-alt text-gray-500 mr-2"></i>
            <span>{{ currentDate }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作按钮（新增管理费条款按钮） -->
    <div class="quick-actions mt-4 bg-light p-3 rounded-lg shadow-sm">
      <router-link to="/admin/customer/add" class="btn btn-primary">
        <i class="fa fa-user-plus mr-2"></i>添加客户
      </router-link>
      <!-- 员工录入按钮 -->
      <router-link to="/register" class="btn btn-success">
        <i class="fa fa-user-tie mr-2"></i>员工录入
      </router-link>
      <router-link to="/admin/statistics" class="btn btn-warning">
        <i class="fa fa-chart-line mr-2"></i>数据统计
      </router-link>
      <router-link to="/admin/change-password" class="btn btn-dark">
        <i class="fa fa-key mr-2"></i>修改密码
      </router-link>
      <!-- 新增：管理费条款按钮 -->
      <router-link to="/admin/management-fee-terms" class="btn btn-info">
        <i class="fa fa-file-alt mr-2"></i>管理废条款
      </router-link>
    </div>

    <!-- 主要内容区 - 左右分栏布局 -->
    <div class="main-content mt-4">
      <div class="row gap-4">
        <!-- 左侧：管理数据统计卡片 -->
        <div class="col-lg-8">
          <div class="p-3 bg-white rounded-lg shadow-sm">
            <h3 class="mb-4 pb-2 border-bottom">系统数据统计</h3>
            <div class="stats-cards" v-if="!loading">
              <div class="row gap-3">
                <div class="col-md-6">
                  <div class="card bg-light hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">待审核合同</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ pendingAuditCount }}</span>
                            <span class="stat-desc">份合同等待审核</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-primary text-white p-2">
                          <i class="fa fa-clipboard-check"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToAuditContracts" class="card-link mt-3 d-inline-block">查看详情</a>
                    </div>
                  </div>
                </div>

                <div class="col-md-6">
                  <div class="card bg-warning text-dark hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">新增客户</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ newCustomerCount }}</span>
                            <span class="stat-desc">位新客户待跟进</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-warning text-dark p-2">
                          <i class="fa fa-user-plus"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToNewCustomers" class="card-link mt-3 d-inline-block">查看详情</a>
                    </div>
                  </div>
                </div>

                <div class="col-md-6">
                  <div class="card bg-success text-white hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">合同总数</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ totalContractCount }}</span>
                            <span class="stat-desc">份有效合同</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-success text-white p-2">
                          <i class="fa fa-file-contract"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToAllContracts" class="card-link mt-3 d-inline-block text-light">查看详情</a>
                    </div>
                  </div>
                </div>

                <div class="col-md-6">
                  <div class="card bg-dark text-white hover-effect">
                    <div class="card-body">
                      <div class="d-flex justify-content-between align-items-start">
                        <div>
                          <h5 class="card-title mb-1">客户总数</h5>
                          <p class="card-text text-muted mb-0">
                            <span class="stat-number">{{ totalCustomerCount }}</span>
                            <span class="stat-desc">位注册客户</span>
                          </p>
                        </div>
                        <div class="icon-circle bg-gray-600 text-white p-2">
                          <i class="fa fa-users"></i>
                        </div>
                      </div>
                      <a href="#" @click="goToAllCustomers" class="card-link mt-3 d-inline-block text-light">查看详情</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：日历 & 快速统计 -->
        <div class="col-lg-4">
          <!-- 日历组件 -->
          <div class="p-3 bg-white rounded-lg shadow-sm mb-4">
            <h3 class="mb-4 pb-2 border-bottom">本月日历</h3>
            <div class="calendar">
              <div class="calendar-header">
                <div class="month-year">{{ currentMonthName }} {{ currentYear }}</div>
              </div>
              <div class="calendar-days">
                <div class="day-header">日</div>
                <div class="day-header">一</div>
                <div class="day-header">二</div>
                <div class="day-header">三</div>
                <div class="day-header">四</div>
                <div class="day-header">五</div>
                <div class="day-header">六</div>

                <!-- 日历天数 - 标出当前日期 -->
                <div v-for="day in 42" :key="day" class="calendar-day">
                  <div
                      v-if="day <= daysInMonth"
                      :class="{ 'current-day': isCurrentDay(day) }"
                      class="day-number"
                  >
                    {{ day }}
                  </div>
                </div>
              </div>
              <div class="d-flex justify-content-end mt-3">
                <button @click="prevMonth" class="btn btn-sm btn-outline-primary mr-2">
                  <i class="fa fa-chevron-left"></i>
                </button>
                <button @click="nextMonth" class="btn btn-sm btn-outline-primary">
                  <i class="fa fa-chevron-right"></i>
                </button>
              </div>
            </div>
          </div>

          <!-- 快速统计卡片 -->
          <div class="p-3 bg-white rounded-lg shadow-sm">
            <h3 class="mb-4 pb-2 border-bottom">近期数据概览</h3>
            <div class="quick-stats">
              <div class="stat-item d-flex justify-content-between p-2 border-bottom">
                <div>
                  <p class="text-sm text-muted mb-0">本周新增客户</p>
                </div>
                <div class="text-right">
                  <p class="stat-value font-weight-bold">{{ weeklyNewCustomers }}</p>
                  <p class="text-xs text-success"><i class="fa fa-arrow-up"></i> 12%</p>
                </div>
              </div>
              <div class="stat-item d-flex justify-content-between p-2 border-bottom">
                <div>
                  <p class="text-sm text-muted mb-0">本月合同完成率</p>
                </div>
                <div class="text-right">
                  <p class="stat-value font-weight-bold">{{ monthlyContractRate }}%</p>
                  <p class="text-xs text-success"><i class="fa fa-arrow-up"></i> 5%</p>
                </div>
              </div>
              <div class="stat-item d-flex justify-content-between p-2 border-bottom">
                <div>
                  <p class="text-sm text-muted mb-0">客户满意度</p>
                </div>
                <div class="text-right">
                  <p class="stat-value font-weight-bold">{{ satisfactionRate }}%</p>
                  <p class="text-xs text-danger"><i class="fa fa-arrow-down"></i> 2%</p>
                </div>
              </div>
              <div class="stat-item d-flex justify-content-between p-2">
                <div>
                  <p class="text-sm text-muted mb-0">待处理工单</p>
                </div>
                <div class="text-right">
                  <p class="stat-value font-weight-bold">{{ pendingWorkOrders }}</p>
                  <p class="text-xs text-danger"><i class="fa fa-arrow-up"></i> 8%</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container mt-4">
      <div class="spinner"></div>
      <p>加载统计数据中...</p>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-container mt-4">
      <div class="error-message">
        <i class="fa fa-exclamation-circle mr-2"></i>{{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { computed, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'AdminManage',
  setup() {
    const store = useStore()
    const router = useRouter()

    // 用户信息
    const admin = computed(() => store.state.admin || { contactName: '管理员' })

    // 统计数据
    const pendingAuditCount = ref(0)      // 待审核合同数
    const newCustomerCount = ref(0)       // 新增客户数
    const totalContractCount = ref(0)     // 合同总数
    const totalCustomerCount = ref(0)     // 客户总数
    const weeklyNewCustomers = ref(0)     // 本周新增客户
    const monthlyContractRate = ref(0)    // 本月合同完成率
    const satisfactionRate = ref(0)       // 客户满意度
    const pendingWorkOrders = ref(0)      // 待处理工单

    // 日历相关
    const currentDate = ref('')
    const currentMonth = ref(new Date().getMonth())
    const currentYear = ref(new Date().getFullYear())
    const currentMonthName = ref('')
    const daysInMonth = ref(0)

    // 天气相关
    const weatherInfo = ref({
      temp: '加载中',
      description: '获取天气中...'
    })

    // 加载状态和错误信息
    const loading = ref(true)
    const errorMessage = ref('')

    // 判断是否为当前日期
    const isCurrentDay = (day) => {
      const now = new Date()
      return (
          day === now.getDate() &&
          currentMonth.value === now.getMonth() &&
          currentYear.value === now.getFullYear()
      )
    }

    // 获取管理统计数据
    const fetchAdminStats = () => {
      loading.value = true
      errorMessage.value = ''

      // 模拟获取统计数据（实际项目中替换为API调用）
      pendingAuditCount.value = Math.floor(Math.random() * 10)
      newCustomerCount.value = Math.floor(Math.random() * 15)
      totalContractCount.value = Math.floor(Math.random() * 100) + 50
      totalCustomerCount.value = Math.floor(Math.random() * 500) + 100
      weeklyNewCustomers.value = Math.floor(Math.random() * 20)
      monthlyContractRate.value = Math.floor(Math.random() * 20) + 70
      satisfactionRate.value = Math.floor(Math.random() * 10) + 80
      pendingWorkOrders.value = Math.floor(Math.random() * 15)

      loading.value = false
    }

    // 导航方法
    const goToAuditContracts = () => {
      router.push('/admin/contract/audit')
    }

    const goToNewCustomers = () => {
      router.push('/admin/customer/new')
    }

    const goToAllContracts = () => {
      router.push('/admin/contract/list')
    }

    const goToAllCustomers = () => {
      router.push('/admin/customer/list')
    }

    const logout = () => {
      localStorage.removeItem('admin')
      store.commit('setAdmin', null)
      router.push('/login')
    }

    // 获取当前日期和日历信息
    const updateDateInfo = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth()
      const day = now.getDate()
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']

      currentDate.value = `${year}年${month + 1}月${day}日 ${days[now.getDay()]}`
      currentMonth.value = month
      currentYear.value = year
      currentMonthName.value = monthNames[month]

      // 计算当月天数
      daysInMonth.value = new Date(year, month + 1, 0).getDate()
    }

    // 获取天气信息 (使用模拟数据)
    const fetchWeather = () => {
      const weatherData = {
        temp: Math.floor(Math.random() * 30) + 10,
        description: ['晴天', '多云', '小雨', '阴天'][Math.floor(Math.random() * 4)]
      }
      weatherInfo.value = weatherData
    }

    // 切换月份
    const prevMonth = () => {
      currentMonth.value = (currentMonth.value - 1 + 12) % 12
      if (currentMonth.value === 11) {
        currentYear.value--
      }
      const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
      currentMonthName.value = monthNames[currentMonth.value]
      daysInMonth.value = new Date(currentYear.value, currentMonth.value + 1, 0).getDate()
    }

    const nextMonth = () => {
      currentMonth.value = (currentMonth.value + 1) % 12
      if (currentMonth.value === 0) {
        currentYear.value++
      }
      const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
      currentMonthName.value = monthNames[currentMonth.value]
      daysInMonth.value = new Date(currentYear.value, currentMonth.value + 1, 0).getDate()
    }

    // 组件生命周期
    onMounted(() => {
      updateDateInfo()
      fetchWeather()
      fetchAdminStats()

      // 每月1日自动更新日历
      const date = new Date()
      if (date.getDate() === 1) {
        updateDateInfo()
      }

      // 每天更新日期和天气
      setInterval(() => {
        updateDateInfo()
        fetchWeather()
      }, 24 * 60 * 60 * 1000)
    })

    return {
      adminName: admin.value.contactName || '系统管理员',
      pendingAuditCount,
      newCustomerCount,
      totalContractCount,
      totalCustomerCount,
      weeklyNewCustomers,
      monthlyContractRate,
      satisfactionRate,
      pendingWorkOrders,
      currentDate,
      currentMonthName,
      currentYear,
      daysInMonth,
      weatherInfo,
      prevMonth,
      nextMonth,
      isCurrentDay,
      loading,
      errorMessage,
      logout,
      goToAuditContracts,
      goToNewCustomers,
      goToAllContracts,
      goToAllCustomers
    }
  }
}
</script>

<style scoped>
.admin-manage {
  padding: 20px;
  max-width: 100%;
}

.header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.header-content {
  width: 100%;
}

.welcome-section {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.quick-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.btn {
  display: inline-flex;
  align-items: center;
  padding: 10px 18px;
  border-radius: 6px;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
  font-size: 14px;
  border: none;
}

.btn-primary { background-color: #3498db; color: white; box-shadow: 0 4px 6px rgba(52, 152, 219, 0.2); }
.btn-secondary { background-color: #7f8c8d; color: white; box-shadow: 0 4px 6px rgba(127, 140, 141, 0.2); }
.btn-info { background-color: #34c6d3; color: white; box-shadow: 0 4px 6px rgba(52, 198, 211, 0.2); }
.btn-warning { background-color: #f39c12; color: #212529; box-shadow: 0 4px 6px rgba(243, 156, 18, 0.2); }
.btn-success { background-color: #27ae60; color: white; box-shadow: 0 4px 6px rgba(39, 174, 96, 0.2); }
.btn-dark { background-color: #2c3e50; color: white; box-shadow: 0 4px 6px rgba(44, 62, 80, 0.2); }

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
}

.main-content .row {
  display: flex;
  gap: 20px;
}

.main-content .col-lg-8 {
  flex: 1;
}

.main-content .col-lg-8 > div {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.stats-cards .card {
  border: none;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  margin-bottom: 15px;
  background-color: white;
}

.stats-cards .card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stats-cards .card-body {
  padding: 18px;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  margin-right: 10px;
  display: block;
}

.stat-desc {
  font-size: 14px;
  color: #6c757d;
  display: block;
}

.card-link {
  color: #3498db;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s;
}

.card-link:hover {
  color: #2980b9;
  text-decoration: underline;
}

.main-content .col-lg-4 {
  flex: 0 0 300px;
  max-width: 300px;
}

.main-content .col-lg-4 > div {
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.calendar {
  padding: 15px;
}

.calendar-header {
  margin-bottom: 15px;
  text-align: center;
}

.month-year {
  font-size: 18px;
  font-weight: 600;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.day-header {
  text-align: center;
  font-weight: 500;
  padding: 5px;
  color: #6c757d;
}

.calendar-day {
  text-align: center;
  padding: 5px;
  min-height: 30px;
}

.day-number {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.current-day {
  background-color: #3498db;
  color: white;
  font-weight: 600;
}

.quick-stats {
  padding: 0;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-value {
  font-size: 18px;
}

.text-success {
  color: #28a745;
}

.text-danger {
  color: #dc3545;
}

.loading-container {
  text-align: center;
  padding: 50px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  text-align: center;
  padding: 50px;
}

.error-message {
  color: #e74c3c;
  font-size: 16px;
  padding: 10px;
  border-radius: 4px;
  background-color: #f8d7da;
  display: inline-block;
}

.icon-circle {
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.hover-effect {
  transition: transform 0.3s, box-shadow 0.3s;
}

.hover-effect:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
</style>